package system;

import java.io.IOException;
import java.net.Socket;

import observer.ElevatorDataCollection;
import observer.ElevatorPartialStruct;

import network.client.PersonDispatcherElevatorThread;

import messages.BaseMessage;
import messages.MessageFactory;
import messages.MessageType;
import messages.observer.CurrentStateMessage;
import messages.observer.CurrentStateRequest;

import state.group.ElevatorStruct;
import state.group.GroupDispatcherState;
import state.person.PersonDispatcherState;

public class GlobalData {
    
    public static int LISTEN_PORT;
    
    public static final PersonDispatcherState state = new PersonDispatcherState();
    
    public static GroupDispatcherState groupState;
    
    public static ElevatorDataCollection partialState = new ElevatorDataCollection();
    
    public static PersonDispatcherElevatorThread elevatorThread;
    
    public static void loadGroupDispatcherState(Socket groupDispatcherSocket) throws IOException
    {
        
        CurrentStateRequest message = new CurrentStateRequest();
        
        groupDispatcherSocket.getOutputStream().write(message.toByteArray());
        
        BaseMessage reply = MessageFactory.readMessage(groupDispatcherSocket);
        
        if (reply.getMessageType().equals(MessageType.CurrentStateMessage));
        {
            CurrentStateMessage stateMessage = (CurrentStateMessage) reply;
            
            setGroupDispatcherState(stateMessage);
        }
        
    }
    
    public static void setGroupDispatcherState(CurrentStateMessage message) throws IOException
    {
        GroupDispatcherState newState = message.getDispatcherState();
        
        synchronized (GlobalData.class)
        {
            synchronized (partialState)
            {
                groupState = newState;
                
                for (Byte id : groupState.elevatorData.keySet())
                {
                    ElevatorPartialStruct partialStruct = partialState.get(id);
                    if (partialStruct == null)
                    {
                        partialStruct = new ElevatorPartialStruct();
                        partialState.put(id, partialStruct);
                    }
                    ElevatorStruct struct = groupState.elevatorData.get(id);
                    
                    partialStruct.setDirection(struct.direction);
                    partialStruct.setDoorOpen(struct.doorOpen);
                    partialStruct.setIdentifier(struct.identifier);
                    partialStruct.setLastKnownFloor(struct.lastKnownFloor);
                }
            }
        }
    }
    
}
